package handle

import (
	"encoding/json"
	"fmt"
	"gitee.com/git_public/vfaith/builtin/vault"
	"html/template"
	"log"
	"net/http"
	"path/filepath"
)

//region 结构体定义

type BlendHttp struct {
	W http.ResponseWriter
	R *http.Request
}

func NewBlendHttp(w http.ResponseWriter, r *http.Request) *BlendHttp {
	return &BlendHttp{W: w, R: r}
}

func (bHttp *BlendHttp) GetWriter() http.ResponseWriter {
	return bHttp.W
}

func (bHttp *BlendHttp) GetRequest() *http.Request {
	return bHttp.R
}

func (bHttp *BlendHttp) WriteErrorStr(err error, errStr string) bool {
	if err == nil {
		return false
	}

	log.Print(err)
	http.Error(bHttp.W, errStr, http.StatusInternalServerError)
	return true
}

func (bHttp *BlendHttp) WriteError(err error) bool {
	if err == nil {
		return false
	}

	bHttp.WriteErrorStr(err, fmt.Sprintf("应用程序内部错误：【%s】", err))
	return true
}

func (bHttp *BlendHttp) WriteErrorJSON(err error) bool {
	return bHttp.WriteError(err)
}

func (bHttp *BlendHttp) WriteSuccessJSON() {
	bHttp.WriteJSON("success")
}

func (bHttp *BlendHttp) WriteJSON(data any) {
	w := bHttp.W

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 返回 JSON 响应
	if err := json.NewEncoder(w).Encode(data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

//endregion

//region 文本信息返回

func (bHttp *BlendHttp) ReturnError(errInfo string) {
	w := bHttp.W
	http.Error(w, fmt.Sprintf("Internal Server Error：【%s】", errInfo), http.StatusInternalServerError)
}

func (bHttp *BlendHttp) ReturnText(text string) {
	w := bHttp.W
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	_, _ = fmt.Fprintf(w, text)
}

func (bHttp *BlendHttp) ReturnHTML(html string) {
	w := bHttp.W
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	_, _ = fmt.Fprintf(w, "<!DOCTYPE html><html><head><title>JSON Output</title></head><body>%s</body></html>", html)
}

//endregion

// region ListDataHandle

func (bHttp *BlendHttp) ReturnListData(data vault.IxBundleData, param ...string) error {
	//List呈现方式：ViewPage、Json、Excel
	//Model呈现方式：ViewPage、EditPage、Json、Excel

	if len(param) > 0 {
		if param[0] == "excel" {
			//返回excel文件
			//ReturnExcel(w, data)
		} else {
			//返回模板页面
			//bHttp.RenderPage(data, param[0])
		}
	} else {
		//返回JSON数据
		bHttp.ReturnJson(data)
	}

	return nil
}

func (bHttp *BlendHttp) ReturnJson(data any) {
	w := bHttp.W

	// 打印结果
	//for _, row := range data.Rows {
	//	fmt.Println(row)
	//}

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 返回 JSON 响应
	if err := json.NewEncoder(w).Encode(data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func (bHttp *BlendHttp) RenderPage(data *vault.BundlePage, tmplPath string) {
	w := bHttp.W

	// 打印结果
	//for _, row := range data.Rows {
	//	fmt.Println(row)
	//}

	//newTmpl, err := template.New(filepath.Base(tmplPath)).Funcs(GetTemplateFunc()).ParseFiles(tmplPath)
	//newTmpl, err = template.New(filepath.Base(tmplPath)).Funcs(GetTemplateFunc()).ParseFS(embed.FsDashboardTmpl, basePath+tmplPath)

	fileBasePath := "resources/template/"
	newTmpl, e1 := template.New(filepath.Base(tmplPath)).Funcs(GetTemplateFunc()).ParseFiles(fileBasePath + tmplPath)

	if bHttp.WriteError(e1) {
		log.Print(fmt.Errorf("HTML模板创建异常：%v", e1))
		return
	}

	e2 := newTmpl.Execute(w, data)
	if bHttp.WriteError(e2) {
		log.Print(fmt.Errorf("HTML模板渲染异常：%v", e1))
	}
}

func (bHttp *BlendHttp) RenderTmpl(data any, tmplPath string) {
	w := bHttp.W

	fileBasePath := "resources/template/"
	newTmpl, e1 := template.New(filepath.Base(tmplPath)).Funcs(GetTemplateFunc()).ParseFiles(fileBasePath + tmplPath)

	if bHttp.WriteError(e1) {
		log.Print(fmt.Errorf("HTML模板创建异常：%v", e1))
		return
	}

	e2 := newTmpl.Execute(w, data)
	if bHttp.WriteError(e2) {
		log.Print(fmt.Errorf("HTML模板渲染异常：%v", e1))
	}
}

//endregion
